package com.czl.module_service.viewmodel.inventory

import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.AreaIdBean
import com.czl.base.data.bean.ImgRspBean
import com.czl.base.data.bean.tengyun.*
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.czl.module_base.widget.timeselector.TimeSelector
import java.util.*


class AssetRegisterViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    val uc = UiChangeEvent()

    var isHideArr = arrayListOf<String>("否", "是")
    var gainMethodArr = arrayListOf<String>(
        "外购",
        "馈赠",
        "划拨",
        "工程转资产",
        "投资者投入",
        "非货币性资产交换",
        "债务重组",
        "企业合并",
        "融资租赁",
        "委托",
        "租赁"
    )
    var projectMap: HashMap<String, AreaIdBean> = hashMapOf()
    var companyMap: HashMap<String, CompanyBean> = hashMapOf()
    var orgMap: HashMap<String, OrgBean> = hashMapOf()
    var userMap: HashMap<String, UserBean> = hashMapOf()
    var classificationList: List<CategoryBean> = arrayListOf()
    var taskId: Long? = 0
    var taskName: String? = ""
    var execId: String? = ""

    // beaninfo
    var projectId: String = ""
    var projectObs = ObservableField(model.getAreaName())
    var classificationId: Int = 0
    var classificationObs = ObservableField("")
    var facilityNameObs = ObservableField("")
    var facilityNoObs = ObservableField("")
    var productNoObs = ObservableField("")
    var brandObs = ObservableField("")
    var productModelObs = ObservableField("")
    var unitObs = ObservableField("")
    var vendorObs = ObservableField("")
    var supplyObs = ObservableField("")
    var gainMethod: Int? = 0
    var gainMethodObs = ObservableField("")
    var gainDateObs = ObservableField("")
    var priceObs = ObservableField("")
    var isHide: Int = 0
    var isHideObs = ObservableField("否")
    var markObs = ObservableField("")
    var picUrl = ""
    var fileParamUrl = ObservableField("")
    var manageCompanyId: Int = 0
    var manageCompanyObs = ObservableField("")
    var manageOrgId: Int = 0
    var manageOrgObs = ObservableField("")
    var manageUserId: Int = 0
    var manageUserObs = ObservableField("")
    var parentCompany: OwnerCompanyBean = OwnerCompanyBean()
    var parentCompanyObs = ObservableField(model.getLocalUserInfo()?.companyName)


    class UiChangeEvent {
        val loadChangeEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val loadBackEvent: SingleLiveEvent<Int> = SingleLiveEvent()
    }

    val selectedSubmit: BindingCommand<Void> = BindingCommand(BindingAction {
        save()
    })

    val onImageClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(99)
    })
    val getIsHideObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(1)
    })
    var getAreaObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
//        uc.loadChangeEvent.postValue(2)
    })
    var getGainMethodObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(3)
    })
    var getManageCompanyObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(4)
    })
    var getParentCompanyObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(5)
    })
    var getManageOrgObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(6)
    })
    var getManageUserObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(7)
    })
    var getFainDateObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(8)
    })
    var getClassificationObsInfo: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.loadChangeEvent.postValue(9)
    })

    fun getIdByNeighNo() {
        model.mTengYunHttpDataSource.getIdByNeighNo(
            GsonUtils.toJson(
                mapOf(
                    "neighNo" to model.getAreaId()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Int>>() {
                override fun onResult(t: BaseBean<Int>) {
                    if (t.state == 0) {
                        projectId = t.data.toString()
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun getBaseInfo() {
//        projectId = model.getAreaId()
//        projectObs.set(model.getAreaName())
        for (bean in model.getAreaList()) {
            projectMap.put(bean.areaName, bean)
        }
        parentCompany.companyId = model.getLoginCompanyId()
        parentCompany.companyName = model.getLocalUserInfo()?.companyName
        parentCompany.companyRatio = "100"
        parentCompany.companyShortName = model.getLocalUserInfo()?.companyName
        getCompanyList()
        getStorehousePropClass()
    }

    fun checkInfo(bean: FacilityBean): Boolean {
        if (bean.projectId == null || bean.projectId!!.isEmpty() || bean.projectId == "") {
            showNormalToast("请选择项目！")
            return true
        }
        if (bean.classificationId ==null || bean.classificationId!!.isEmpty() || bean.classificationId == "0") {
            showNormalToast("请选择资产分类！")
            return true
        }
        if (bean.facilityName == null || bean.facilityName!!.isEmpty()) {
            showNormalToast("请输入资产名称！")
            return true
        }
        if (bean.facilityNo == null || bean.facilityNo!!.isEmpty()) {
            showNormalToast("请选择资产分类！")
            return true
        }
        if (bean.model == null || bean.model!!.isEmpty()) {
            showNormalToast("请输入资产型号！")
            return true
        }
        if (bean.unit == null || bean.unit!!.isEmpty()) {
            showNormalToast("请输入资产单位！")
            return true
        }
        if (bean.gainMethod == null || bean.gainMethod!! < 1) {
            showNormalToast("请选择取得方式！")
            return true
        }
        if (bean.gainDate == null || bean.gainDate!!.isEmpty()) {
            showNormalToast("请选择取得日期！")
            return true
        }
        if (bean.price == null || bean.price!!.isEmpty()) {
            showNormalToast("请输入资产原值！")
            return true
        }
        return false
    }

    fun save() {
        val facilityBean = FacilityBean()
        facilityBean.companyId = model.getLoginCompanyId()
        facilityBean.projectName = projectObs.get()
        facilityBean.projectId = projectId
        facilityBean.brand = brandObs.get()
        facilityBean.productNo = productNoObs.get()
        facilityBean.facilityName = facilityNameObs.get()
        facilityBean.model = productModelObs.get()
        facilityBean.mark = markObs.get()
        facilityBean.facilityNo = facilityNoObs.get()
        facilityBean.unit = unitObs.get()
        facilityBean.producer = vendorObs.get()
        facilityBean.supply = supplyObs.get()
        facilityBean.gainMethod = gainMethod
        facilityBean.gainDate = gainDateObs.get()
        facilityBean.classificationId = classificationId.toString()
        facilityBean.price = priceObs.get()
        facilityBean.facilitySum = 1
        facilityBean.manageCompanyId = manageCompanyId
        facilityBean.manageOrgId = manageOrgId
        facilityBean.manageUserId = manageUserId?.toLong()
        facilityBean.ownershipCompanyList = arrayListOf<OwnerCompanyBean>(parentCompany)
        facilityBean.isHide = this.isHide
        facilityBean.picUrl = picUrl
        if (checkInfo(facilityBean)) {
            return
        }

//        Log.e(">>>", GsonUtils.getGson().toJson(facilityBean))
        addFacility(facilityBean)
    }

    private fun addFacility(facilityBean: FacilityBean) {
        model.mTengYunHttpDataSource.addProfitFacility(
            GsonUtils.toJson(
                facilityBean
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<FacilityBean>>() {
                override fun onResult(t: BaseBean<FacilityBean>) {
                    if (t.errorCode == 0) {
                        tempCheck(t.data?.id)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun tempCheck(
        id: Long?
    ) {
        model.mTengYunHttpDataSource.summaryInventoryFacility(
            GsonUtils.toJson(
                mapOf(
                    "facilityid" to id,
                    "isReplace" to 0,// 是否代盘 0 否   1 是
                    "inventoryMethod" to 2,  // 盘点方式 0 拍照   1扫码   2 人工盘
                    "status" to 2,
                    "planInventoryMethod" to 1,
                    "tname" to model.getLocalUserInfo()?.nickName,
                    "userId" to model.getLocalUserInfo()?.userId,
                    "taskId" to taskId   // 任务id
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.errorCode == 0) {
                        showNormalToast("提交成功")
                        uc.loadBackEvent.postValue(0)
                        LiveBusCenter.postRegisterResultReturnEvent(0)
                        // 返回盘点页面
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    private fun getCompanyList() {
        model.mTengYunHttpDataSource.selectCompanyByModule(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<CompanyBean>>>() {
                override fun onResult(t: BaseBean<ListBean<CompanyBean>>) {
                    if (t.errorCode == 0) {
                        for (bean in t.data?.list!!) {
                            companyMap.put(bean.companyName!!, bean)
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun getManageOrgList() {
        model.mTengYunHttpDataSource.selectOrganization(
            GsonUtils.toJson(
                mapOf(
                    "companyId" to manageCompanyId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<OrgBean>>>() {
                override fun onResult(t: BaseBean<ListBean<OrgBean>>) {
                    if (t.errorCode == 0) {
                        val allChildOrgList =
                            getAllChildOrgList(t.data?.list as MutableList<OrgBean>)
                        for (bean in allChildOrgList) {
                            orgMap.put(bean.orgName!!, bean)
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun getManageUseList() {
        model.mTengYunHttpDataSource.getUserListByOrgIds(
            GsonUtils.toJson(
                mapOf(
                    "orgIds" to arrayListOf<Int>(manageOrgId)
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<MutableList<UserBean>>>() {
                override fun onResult(t: BaseBean<MutableList<UserBean>>) {
                    if (t.errorCode == 0) {
                        for (bean in t.data!!) {
                            userMap.put(bean.tname!!, bean)
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    private fun getStorehousePropClass() {
        model.mTengYunHttpDataSource
            .getclassificationlistCompany(
                GsonUtils.toJson(
                    mapOf(
                        "companyId" to model.getLocalUserInfo()?.companyId,
                        "classStatusList" to arrayOf(0, 2)
                    )
                )
            )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe {
                showLoading()
            }
            .subscribe(object : ApiSubscriberHelper<BaseBean<List<CategoryBean>>>() {
                override fun onResult(t: BaseBean<List<CategoryBean>>) {
                    dismissLoading()
                    if (t.errorCode == 0) {
                        t.data?.let {
                            classificationList = it
                        }
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun uploadHeadImg(imgSrc: String) {
        model.apply {
            uploadHeadImg("szchd", imgSrc, "assets")
                .compose(RxThreadHelper.rxSchedulerHelper(this@AssetRegisterViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.data == null) return
                        if (t.code == 200) {
                            val bean: ImgRspBean = t.data!!
                            fileParamUrl.set(bean.url)
                            picUrl = bean.url
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }

    fun getFacilityNoByRule(classificationCode : String?) {
        model.mTengYunHttpDataSource
            .getFacilityNoByRule(
                GsonUtils.toJson(
                    mapOf(
                        "projectId" to projectId,
                        "companyId" to model.getLocalUserInfo()?.companyId,
                        "classificationCode" to classificationCode
                    )
                )
            )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe {
                showLoading()
            }
            .subscribe(object : ApiSubscriberHelper<BaseBean<String?>>() {
                override fun onResult(t: BaseBean<String?>) {
                    dismissLoading()
                    if (t.state == 0) {
                        facilityNoObs.set(t.data)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }
}